package com.geeguo.ebuilder.client.base.database.consumer;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.geeguo.ebuilder.client.base.core.constants.MQConsumerGroupConstants;
import com.geeguo.ebuilder.client.base.core.constants.MQTopicConstants;
import com.geeguo.ebuilder.core.common.utils.worker.WorkerIdHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQPushConsumerLifecycleListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;

@Slf4j
@Component
@RocketMQMessageListener(topic = MQTopicConstants.DATA_SOURCE_INFO_CHANGE, consumerGroup = MQConsumerGroupConstants.CLIENT_DATA_SOURCE_INFO_CHANGE, messageModel = MessageModel.BROADCASTING)
public class DataSourceInfoChangeMQConsumer implements RocketMQListener<String>, RocketMQPushConsumerLifecycleListener {

    @Autowired
    private DataSource dataSource;

    @Override
    public void prepareStart(DefaultMQPushConsumer consumer) {
        consumer.setInstanceName(String.valueOf(WorkerIdHelper.getWorkerId()));
    }

    @Override
    public void onMessage(String id) {
        log.info("收到数据源信息变更消息：" + id);
        DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
        ds.removeDataSource(id);
    }
}
